#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>
#include <pthread.h>
#include <string.h>
#include <semaphore.h>

#define ERRLOG() printf("[file:%s][func:%s][line:%d]\n",__FILE__,__func__,__LINE__);
#define INFO(fmt,...) printf(fmt,##__VA_ARGS__);

sem_t sem;
sem_t sem2;
sem_t sem3;

void handler(int arg){
    // sem_destroy(&sem);
    // sem_destroy(&sem2);
    // sem_destroy(&sem3);
    exit(0);
}

void* pthread_function(void* arg){
    pthread_detach(pthread_self());
    while(1){
        sleep(1);
        sem_wait(&sem);
        puts("AAA");
        sem_post(&sem2);
    }
}

void* pthread_function2(void* arg){
    pthread_detach(pthread_self());
    while(1){
        sem_wait(&sem2);
        puts("BBB");
        sem_post(&sem3);
    }  
}

void* pthread_function3(void* arg){
    pthread_detach(pthread_self());
    while(1){
        sem_wait(&sem3);
        puts("CCC");
        sem_post(&sem);
    }  
}


int main(int argc, char const *argv[])
{   
    signal(SIGINT,handler);
    pthread_t pthread;
    sem_init(&sem,0,1);
    sem_init(&sem2,0,0);
    sem_init(&sem3,0,0);
    if(pthread_create(&pthread,NULL,pthread_function,NULL)!=0){
        ERRLOG();
        exit(-1);
    }

    if(pthread_create(&pthread,NULL,pthread_function2,NULL)!=0){
        ERRLOG();
        exit(-1);
    }

    if(pthread_create(&pthread,NULL,pthread_function3,NULL)!=0){
        ERRLOG();
        exit(-1);
    }
    while(1);
    return 0;
}
